package com.limanyik.family.oss.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.limanyik.family.common.entity.BasisDictGroup;
import com.limanyik.family.oss.entity.DictTreeVo;
import com.limanyik.family.oss.mapper.BasisDictGroupMapper;
import com.limanyik.family.oss.service.BasisDictGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统-字典表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2021-11-24
 */
@Service
public class BasisDictGroupServiceImpl extends ServiceImpl<BasisDictGroupMapper, BasisDictGroup> implements BasisDictGroupService {

    @Autowired
    BasisDictGroupMapper basisDictGroupMapper;

    /**
     * 获取字典树
     *
     * @return
     */
    @Override
    public List<DictTreeVo> doDictTreeInfoAll() {
        // 字典只存在物理二级存储
        List<BasisDictGroup> basisDictGroups = basisDictGroupMapper.selectList(new QueryWrapper<BasisDictGroup>().eq(BasisDictGroup.DELETE_STATUS, 0));
        // 获取一级节点
        List<BasisDictGroup> stairNodes = basisDictGroups.stream().filter(basisDictGroup -> null == basisDictGroup.getPid()).collect(Collectors.toList());
        List<DictTreeVo> treeVos = new ArrayList<>();
        stairNodes.forEach(basisDictGroup -> {
            DictTreeVo baseNode = treeGenerate(null, basisDictGroup);
            baseNode.setId(basisDictGroup.getId());
            baseNode.setCode(basisDictGroup.getCode());
            baseNode.setTitle(basisDictGroup.getTitle());
            List<BasisDictGroup> screens = basisDictGroups.stream().filter(basisDictGroup1 -> basisDictGroup1.getPid().equals(basisDictGroup.getId())).collect(Collectors.toList());
            // 二级节点
            List<DictTreeVo> secondLevelNodes = new ArrayList<>();
            screens.forEach(basisDictGroup1 -> {
                secondLevelNodes.add(treeGenerate(null, basisDictGroup1));
            });
            baseNode.setNodes(secondLevelNodes);
            treeVos.add(baseNode);
        });
        return treeVos;
    }

    private DictTreeVo treeGenerate(DictTreeVo dictTreeVo, BasisDictGroup basisDictGroup) {
        dictTreeVo = null == dictTreeVo ? new DictTreeVo() : dictTreeVo;
        if (null == basisDictGroup) {
            return dictTreeVo;
        }
        dictTreeVo.setId(basisDictGroup.getId());
        dictTreeVo.setCode(basisDictGroup.getCode());
        dictTreeVo.setTitle(basisDictGroup.getTitle());
        return dictTreeVo;
    }
}
